#!/bin/bash
#
# /etc/rc.d/rc.sogod
#
# Start/stop/restart the SOGo groupware server.
#
# This script was inspired by the RHEL init.d script present in the
# SOGo source Scripts directory.
#

# These values are defaults. You can update the USER and PREFORK values
# by making changes to /etc/sysconfig/sogo.
USER=sogo
PREFORK=3

PIDFILE=/var/run/sogo/sogo.pid
LOGFILE=/var/log/sogo/sogo.log

if [ -f /etc/sysconfig/sogo ]; then
  . /etc/sysconfig/sogo
fi

DAEMON_OPTS="-WOWorkersCount $PREFORK -WOPidFile $PIDFILE -WOLogFile $LOGFILE"

if [ -z "$GNUSTEP_SYSTEM_ROOT" ]; then
  . /etc/GNUstep/GNUstep.conf
  . ${GNUSTEP_MAKEFILES}/GNUstep.sh
fi

sogo_start() {
  pid="$(cat $PIDFILE 2> /dev/null)"
  if [ -n "$pid" ]; then
    pid="$(ps --pid ${pid} -o pid=)"
    if [ ! -n "$pid" ]; then
      rm -f $PIDFILE
      su - $USER -c "nohup /usr/sbin/sogod $DAEMON_OPTS >/dev/null 2>&1"
      echo "Starting SOGo:  /usr/sbin/sogod $DAEMON_OPTS"
    fi
  else
    su - $USER -c "nohup /usr/sbin/sogod $DAEMON_OPTS >/dev/null 2>&1"
    echo "Starting SOGo:  /usr/sbin/sogod $DAEMON_OPTS"
  fi
}

sogo_stop() {
  pid="$(cat $PIDFILE 2> /dev/null)"
  if [ -n "$pid" ]; then
    pid="$(ps --pid ${pid} -o pid=)"
    if [ -n "$pid" ]; then
      kill $pid >& /dev/null
      echo "Stopping SOGo..."
    fi
  fi
}

case "$1" in
  start)
    sogo_start
    ;;
  stop)
    sogo_stop
    ;;
  restart)
    sogo_stop
    sleep 2
    sogo_start
    ;;
  *)
    sogo_start
esac
